import { hash } from 'ohash'
import { ResOptions } from '../types/types'
interface ReqOption {
    method: string,
    body?: any,
    params?: any,
    headers?: any
}
const fetch = (url: string, options?: any): Promise<any> => {
    //如果token存在 headers添加token
    const cookieToken = useCookie('lin-token')
    const userStore = useUserStore()
    const token = cookieToken.value || userStore.getToken
    options.headers = { LoginType: 'User' }
    if (token) {
        options.headers.Authorization = token
    }
    const { public: { apiBase } } = useRuntimeConfig() // 3.0正式版环境变量要从useRuntimeConfig里的public拿
    const reqUrl = apiBase + url // 你的接口地址
    // 不设置key，始终拿到的都是第一个请求的值，参数一样则不会进行第二次请求
    //const key = hash(JSON.stringify(options) + url)
    // 如果需要统一加参数可以options.params.token = 'xxx'
    return new Promise((resolve, reject) => {
        useFetch(reqUrl, options).then(({ data, error }) => {
            if (error.value) {
                reject(error.value)
                return
            }
            const { value } = data
            const res = value as ResOptions<any>
            // console.log('useFetchResData: ', value)
            if (!value) {
                // 这里处理你自定义的错误，例如code !== 1
                throw createError({
                    statusCode: 500,
                    statusMessage: reqUrl,
                    message: '自己后端接口的报错信息',
                })
            } else if (res.code === 20000) {
                resolve(res.result)
            } else {
                ElMessage.error(res.message)
                reject(res.message)
            }
        }).catch((err: any) => {
            console.log(err)
            reject(err)
        })
    })
}

class Http {

    get = (url: string, params?: any) => {
        return fetch(url, { method: 'get', params })
    }

    post = (url: string, body?: any) => {
        return fetch(url, { method: 'post', body })
    }

    put = (url: string, body?: any) => {
        return fetch(url, { method: 'put', body })
    }

    delete = (url: string, body?: any) => {
        return fetch(url, { method: 'delete', body })
    }
}

export default new Http()